<?php defined('SYSPATH') OR die('No direct access allowed.');
class User_Controller extends Base_Controller
{
	private $userMod;
	public function __construct()
	{
		parent::__construct();
		$this->userMod = new User_Model;
	}

	/**
	 * 用户自己的页面
	 */ 
	public function index()
	{
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		$this->template->head->title = '我的首页';
		$this->template->content = new View('my_index');
		$this->template->content->bind('mycodes',$mycodes);
		$this->template->content->bind('followcodes',$followcodes);
		$this->template->content->bind('favcodes',$favcodes);
		$this->template->content->bind('codeNum',$codeNum);
		$this->template->content->bind('favNum',$favNum);
		$this->template->content->bind('codePagination',$codePagination);
		$this->template->content->bind('favPagination',$favPagination);
		//我发布的代码
		$mycodes = ORM::factory('code')->where('user_id',$this->session->get('userId'))->orderby('id','desc')->find_all(5);
		//发布的代码总数
		$codeNum = ORM::factory('code')->where('user_id',$this->session->get('userId'))->count_all();

		//我收藏的代码
		$favs = Database::instance()->select('code_id')->where('user_id',$this->session->get('userId'))->from('codes_users')->get()->as_array();
		$tmp = array();
		foreach($favs as $val)
		{
			$tmp[] = $val->code_id;
		}
		$favNum = count($tmp);//收藏的代码数
		$favs = array_slice($tmp,0,5);//截取5个
		$favcodes = array();
		if(!empty($favs))
		$favcodes = ORM::factory('code')->in('id',$favs)->find_all();
		//我关注的人发布的代码
		$follows = ORM::factory('follow')->where('user_id',$this->session->get('userId'))->find_all();
		$tmp = array();
		foreach($follows as $val)
		{
			$tmp[] = $val->follow_id;
		}
		$myfollows = $tmp;
		$followcodes = array();
		if(!empty($myfollows))
		$followcodes = ORM::factory('code')->in('user_id',$myfollows)->find_all(5);
		
		$this->_myIndexSidebar($favNum);

		//我发布的代码分页
		$codePagination = new Pagination(array(
			'base_url'		=>	'user/mycodes',
			'total_items'	=>	$codeNum,
			'items_per_page'=>	5,
			)
		);
		//我的收藏代码分页
		$favPagination = new Pagination(array(
			'base_url'		=>	'user/myfavs',
			'total_items'	=>	$favNum,
			'items_per_page'=>	5,
			)
		);
	}

	/**
	 * 我收藏的代码
	 */
	public function myfavs($uri_seg='page',$page=1)
	{
		$items_per_page = 5;
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		$page = (int)$page;
		$page = $page<1?1:$page;

		$favs = Database::instance()->select('code_id')->where('user_id',$this->session->get('userId'))->from('codes_users')->get()->as_array();
		$tmp = array();
		foreach($favs as $val)
		{
			$tmp[] = $val->code_id;
		}
		$favNum = count($tmp);//收藏的代码数
		$favs = $tmp;

		$total_pages = floor($favNum/$items_per_page+1);
		$page = $page>$total_pages?$total_pages:$page;

		$codes = ORM::factory('code')->in('id',$favs)->find_all($items_per_page,($page-1)*$items_per_page);
		$outputCodes = array();
		foreach($codes as $code)
		{
			$tmp = array();
			$tmp['title'] = $code->title;
			$tmp['id'] = $code->id;
			$tmp['username'] = $code->user->username;
			$tmp['user_id'] = $code->user->id;
			$tmp['email'] = $code->user->email;
			$tmp['pubdate'] = date::get_latest_timespan(date::timespan($code->pubdate));
			$tmp['lan'] = $code->lan;
			$tmp['cmtNum'] = $code->comments->count();
			$tmp['favNum'] = $code->users->count();
			$outputCodes[] = $tmp;
		}
		$pagination = new Pagination(array(
			'total_items'	=>	$favNum,
			'items_per_page'=>	$items_per_page,
			'base_url'		=>	'user/myfavs',
			)
		);
		$outputCodes[] = (string)$pagination;
		$this->_ajaxResponse('ok',$outputCodes);
	}

	/**
	 * 我发布的代码
	 */
	public function mycodes($uri_seg='page',$page=1)
	{
		$items_per_page = 5;
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		$page = (int)$page;
		$page = $page<1?1:$page;
		$codeNum = ORM::factory('code')->where('user_id',$this->session->get('userId'))->count_all();
		$total_pages = floor($codeNum/$items_per_page+1);
		$page = $page>$total_pages?$total_pages:$page;

		$codes = ORM::factory('code')->where('user_id',$this->session->get('userId'))->find_all($items_per_page,($page-1)*$items_per_page);
		$outputCodes = array();
		foreach($codes as $code)
		{
			$tmp = array();
			$tmp['title'] = $code->title;
			$tmp['id'] = $code->id;
			$tmp['username'] = $code->user->username;
			$tmp['user_id'] = $code->user->id;
			$tmp['email'] = $code->user->email;
			$tmp['pubdate'] = date::get_latest_timespan(date::timespan($code->pubdate));
			$tmp['lan'] = $code->lan;
			$tmp['cmtNum'] = $code->comments->count();
			$tmp['favNum'] = $code->users->count();
			$outputCodes[] = $tmp;
		}
		$pagination = new Pagination(array(
			'total_items'	=>	$codeNum,
			'items_per_page'=>	$items_per_page,
			'base_url'		=>	'user/mycodes',
			)
		);
		$outputCodes[] = (string)$pagination;
		$this->_ajaxResponse('ok',$outputCodes);
	}
	/**
	 * 用户登录
	 */
	public function login()
	{
		$this->template->content = new View('login');
		$this->template->content->bind('siteName',$siteName);
		$siteName = Kohana::config('core.rpxSiteName');
	}

	/**
	 * 浏览用户的页面
	 * @param int 用户id
	 */ 
	public function view($userId,$pagenum=1)
	{
		$userId = (int)$userId;
		$userInfo = $this->userMod->find($userId);//用户信息
		if(!$userInfo->id)//是否存在该用户
		{
			$this->_popMsg(Kohana::lang('user.usernotexists'));
		}
		$this->template->content = new View('user');
		$this->template->content->bind('user',$user);
		$this->template->content->bind('pageNation',$pageNation);
		$this->template->content->bind('codes',$codes);
		$this->template->content->set('h2',$userInfo->username.'发布的代码');
		$items_per_page = Kohana::config('pagination.default.items_per_page');//每页几条内容
		$user = $userInfo->as_array();//转化成数组
		$codeNum = ORM::factory('code')->where('user_id',$userId)->count_all();//发布的代码总数
		$pageNation = new Pagination(array(
			'total_items'	=>	$codeNum,
			)
		);

		$codes = ORM::factory('code')->where('user_id',$userId)->find_all($items_per_page,($pagenum-1)*$items_per_page);
		//该用户收藏的代码数
		$favNum = Database::instance()->where('user_id',$userId)->count_records('codes_users');

		$this->_userIndexSidebar($userId,$codeNum,$favNum);
	}

	/**
	 * 查看用户的收藏
	 */
	public function viewfav($userId,$pagenum=1)
	{
		$userId = (int)$userId;
		$userInfo = $this->userMod->find($userId);//用户信息
		if(!$userInfo->id)//是否存在该用户
		{
			$this->_popMsg(Kohana::lang('user.usernotexists'));
		}
		$this->template->content = new View('user');
		$this->template->content->bind('user',$user);
		$this->template->content->bind('pageNation',$pageNation);
		$this->template->content->bind('codes',$codes);
		$this->template->content->set('h2',$userInfo->username.'收藏的代码');

		//该用户收藏的代码
		$favs = Database::instance()->select('code_id')->where('user_id',$userId)->from('codes_users')->get()->as_array();
		$tmp = array();
		foreach($favs as $val)
		{
			$tmp[] = $val->code_id;
		}
		$favs = $tmp;
		$favNum = count($favs);//收藏的代码数
		$codeNum = ORM::factory('code')->where('user_id',$userId)->count_all();//发布的代码总数
		$items_per_page = Kohana::config('pagination.default.items_per_page');//每页几条内容
		$user = $userInfo->as_array();//转化成数组
		$codeNum = ORM::factory('code')->where('user_id',$userId)->count_all();//发布的代码总数
		$pageNation = new Pagination(array(
			'total_items'	=>	$codeNum,
			)
		);

		$codes = ORM::factory('code')->in('id',$favs)->find_all($items_per_page,($pagenum-1)*$items_per_page);
		$this->_userIndexSidebar($userId,$codeNum,$favNum);
		
	}

	/**
	 * 关注用户
	 */
	public function follow($followId)
	{
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		$followId = (int)$followId;
		$follow = ORM::factory('follow');
		$followed = $follow->where(array('follow_id'=>$followId,'user_id'=>$this->session->get('userId')))->find();
		if($followed->loaded)//已经是好友了，删除好友关系
		{
			$followed = $follow->where(array('follow_id'=>$followId,'user_id'=>$this->session->get('userId')))->delete();
			$this->_ajaxResponse("suc",array('addFollow'));	
		}
		else//添加好友
		{
			$follow->user_id = $this->session->get('userId');
			$follow->follow_id = $followId;
			$follow->save();
			$this->_ajaxResponse("suc",array('removeFollow'));	
		}
	}

	/**
	 * 验证用户信息
	 */
	public function auth()
	{
		$this->auto_render = false;
		if(isset($_GET['token']) && !empty($_GET['token']))
		{
			$authInfo = $this->userMod->auth($_GET['token']);
			if($authInfo)
			{
				$user = ORM::factory('user')->where(array('identifier'=>$authInfo['identifier']))->find();
				if($user->id)//该用户已存在
				{
					user::set_user(array('userId'=>$user->id,'username'=>$user->username,'email'=>$user->email));
					user::set_login_cookie($user->apikey);
					url::redirect('user');
				}
				else//添加用户
				{
					if($userId = $this->userMod->addUser($authInfo))
					{
						if(!isset($authInfo['email'])) $authInfo['email'] = '';
						user::set_user(array('userId'=>$userId,'username'=>$authInfo['displayName'],'email'=>$authInfo['email']));
						url::redirect('user/setting');
					}
					else
					{
						$this->_popMsg($this->userLang['adderr']);
					}
				}
			}
			else
			{
				$this->_popMsg($this->userLang['loginerr']);
			}
		}
	}

	/**
	 * 用户信息设置
	 */
	public function setting()
	{
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		$this->template->content = new View('setting');
		$userInfo = ORM::factory('user',$this->session->get('userId'));
		$this->template->content->set('userInfo',$userInfo);
	}

	/**
	 * 保存用户设置
	 */
	public function savesetting()
	{
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);

		$this->auto_render = false;
		if(count($this->input->post()))
		{
			$post = new Validation($this->input->post());
			$post->pre_filter('trim')
				->add_rules('email',array('valid','email'),'required')
				->add_rules('username','length[1,24]','required')
				->add_rules('lan','required')
				->add_rules('blogurl','length[0,200]')
				->add_rules('blogname','length[0,100]')
				->add_callbacks('email',array($this,'_uniqueEmail'));
			if(($this->input->post('blogurl')!='')) $post->add_rules('blogurl',array('valid','url'));
			if($post->validate())
			{
				if(ORM::factory('user')->saveSetting($post->as_array()))
				{
					 user::set_user(arr::extract($post->as_array(),'userId','username','email'));
					 $this->_popMsg($this->userLang['savesuc'],'suc');
				}
			}
			else
			{
				$this->_popMsg($post->errors('validation'),'err',url::site('user/setting'));
			}
		}
	}

	/*
	 * 发布代码
	 */
	public function pubcode()
	{
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		//die(Kohana::debug($this->input->post()));
		if(!$_POST)
		{
			$this->template->content = new View('pubcode');
			$userInfo = $this->userMod->find($this->session->get('userId'));
			$this->template->content->set('lans',explode(',',$userInfo->lan));
			$this->template->head->set('title','发布代码');
		}
		else
		{
			$this->auto_render = false;
			$post = new Validation($this->input->post());
			$post->pre_filter('trim')
				->add_rules('title','length[0,150]')
				->add_rules('lan','required','length[1,20]')
				->add_rules('snippet','required')
				->add_rules('intro','length[0,2000]')
				->add_rules('link','length[0,100]');
			if(!empty($_POST['link'])) $post->add_rules('link',array('valid','url'));
			if($post->validate())
			{
				$post = $post->safe_array();
				$code = ORM::factory('code');
				$code->title = $post['title'];
				$code->lan = $post['lan'];
				$code->intro = $post['intro'];
				$code->link = $post['link'];
				$code->pubdate = time();
				$code->user_id = $this->session->get('userId');
				if($code->save())
				{
					$snippetCode = $this->input->raw('post','snippet');
					$snippet = ORM::factory('snippet');
					$snippet->snippet = $snippetCode;
					$snippet->code_id = $code->id;
					$snippet->pubdate = time();
					if($snippet->save())
					{
						//这里应该跳到具体代码页
						$this->_popMsg($this->userLang['addcodesuc'],'suc',url::site('code/detail/'.$code->id));
					}
					else 
						$this->_popMsg($this->userLang['addcodeerr']);
				}
				else
					$this->_popMsg($this->userLang['addcodeerr']);
			}
			else
			{
				$this->_popMsg($post->errors('validation'),'err',url::site('user/pubcode'));
			}
		}
	}

	/**
	 * 编辑代码
	 */
	public function editcode($codeId=0)
	{
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		$codeId = $codeId==0?(int)$this->input->post('code_id'):$codeId;
		$code = ORM::factory('code',(int)$codeId);
		if($code->user_id!=$this->session->get('userId'))
		{
			$this->_popMsg(Kohana::lang('user.noauthority'));
		}
		if(empty($_POST))
		{
			$this->template->content = new View('editcode');
			$this->template->content->code = $code->as_array();
			$this->template->content->bind('snippet',$snippet);
			$this->template->content->set('lans',explode(',',$code->user->lan));//设置语言
			//获取最新代码片段
			$snippetArr = array();
			foreach($code->snippets as $snippet)
			{
				$snippetArr[] = $snippet->as_array();
			}
			$snippet = $snippetArr[0]['snippet'];
		}
		else
		{
			if(!empty($_POST['snippet']))
			{
				$snippetCode = $this->input->raw('post','snippet');
				$snippet = ORM::factory('snippet');
				$snippet->snippet = $snippetCode;
				$snippet->code_id = (int)$this->input->post('code_id');
				$snippet->pubdate = time();
				if($snippet->save())
				{
					//这里应该跳到具体代码页
					$this->_popMsg($this->userLang['editcodesuc'],'suc',url::site('code/detail/'.$code->id));
				}
				else 
					$this->_popMsg($this->userLang['editcodeerr']);	
			}
			else
			{
				$post = new Validation($this->input->post());
				$post->pre_filter('trim')
					->add_rules('title','length[0,150]')
					->add_rules('lan','required','length[1,20]')
					->add_rules('intro','length[0,2000]')
					->add_rules('code_id',array('valid','numeric'))
					->add_rules('link','length[0,100]');
				if(!empty($_POST['link'])) $post->add_rules('link',array('valid','url'));
				if($post->validate())
				{
					$post = $post->safe_array();
					$code = ORM::factory('code',$this->input->post('code_id'));
					$code->title = $post['title'];
					$code->lan = $post['lan'];
					$code->intro = $post['intro'];
					$code->link = $post['link'];
					if($code->save())
					{
						//这里应该跳到具体代码页
						$this->_popMsg($this->userLang['editcodesuc'],'suc',url::site('code/detail/'.$code->id));
					}
					else
					{
						$this->_popMsg($this->userLang['editcodeerr'],'err',url::site('user/editcode/'.$code->id));
					}
				}
				else
				{
					$this->_popMsg($post->errors['validation']);
				}
			}
		}
	}

	/**
	 * 添加评论
	 */
	public function addcmt()
	{
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		if(!empty($_POST))
		{
			$cmt_content = trim($this->input->raw('post','cmt_content'));
			if($cmt_content=='')
			{
				$this->_popMsg(Kohana::lang('comment.emptycmt'));
			}
			else
			{
				$cmt = ORM::factory('comment');
				$codeId = (int)$this->input->post('code_id');
				$cmt->user_id = $this->session->get('userId');
				$cmt->code_id = $codeId;
				$cmt->pubdate = time();
				$cmt->content = $this->input->xss_clean(code::bbcode2html($cmt_content,$this->input->post('brush')));
				if($cmt->save())
				{
					$this->_popMsg(Kohana::lang('comment.addcmtsuc'),'suc',url::site('code/detail/'.$codeId));
				}
				else
				{
					$this->_popMsg(Kohana::lang('comment.addcmterr'));
				}
			}
		}
		else
		{
			$this->_popMsg(Kohana::lang('comment.emptycmt'));
		}
	}

	/**
	 * 登出
	 */
	public function logout()
	{
		$this->session->delete('userId','email','username');
		cookie::delete('auth');
		url::redirect();
	}

	/**
	 * 验证用户的电子邮件是否是唯一
	 *
	 * @param string	email
	 * @return boolean
	 */
	public function _uniqueEmail(Validation $valid)
	{
		//if(!isset($this->session->get('userId')
		$email_exists = (bool)ORM::factory('user')->where(array('email'=>$valid['email'],'id!='=>(int)$this->session->get('userId')))->count_all();
		if($email_exists)
		{
			$valid->add_error('email','duplicate');
		}
	}

	public function fav($codeId)
	{
		$this->auto_render = false;
		$codeId = (int)$codeId;
		if(!user::is_login()) $this->_popMsg($this->userLang['notlogin']);
		$user = $this->userMod->find($this->session->get('userId'));
		if($user->has(ORM::factory('code',$codeId)))
		{
			$user->remove(ORM::factory('code',$codeId));
			if($user->save())
			{
				$this->_ajaxResponse('suc',array('addFav'));
			}
			else
			{
				$this->_ajaxResponse('err',array(Kohana::lang('user.addfaverr')));
			}
		}
		else
		{
			$user->add(ORM::factory('code',$codeId));
			if($user->save())
			{
				$this->_ajaxResponse('suc',array('removeFav'));
			}
			else
			{
				$this->_ajaxResponse('err',array(Kohana::lang('user.removefaverr')));
			}
		}
	}

	/**
	 * 查看用户首页
	 */
	private function _userIndexSidebar($userId,$codeNum,$favNum)
	{
		$this->template->content->bind('codeNum',$codeNum);
		$this->template->content->bind('favNum',$favNum);
		$this->template->content->bind('follow',$follow);
		$this->template->content->bind('following',$following);
		$this->template->content->bind('beingfollowed',$beingfollowed);
		//我是否follow了该用户
		$followMod = ORM::factory('follow');
		$followed = $followMod->where(array('follow_id'=>$userId,'user_id'=>$this->session->get('userId')))->find();
		if($followed->loaded)//已经follow了该用户
		{
			$follow = 'remove';
		}
		else $follow = 'add';

		//该用户follow的用户
		$followers = $followMod->where(array('user_id'=>$userId))->find_all();
		$follows = array();
		foreach($followers as $follower)
		{
			$follows[] = $follower->follow_id;
		}	

		if(!empty($follows))
		{
			$following = Database::instance()->select('id','username','email')->in('id',$follows)->get('users')->as_array();
		}

		//谁关注这个人
		$followers = $followMod->where(array('follow_id'=>$userId))->find_all();
		$follows = array();
		foreach($followers as $follower)
		{
			$follows[] = $follower->user_id;
		}	

		if(!empty($follows))
		{
			$beingfollowed = Database::instance()->select('id','username','email')->in('id',$follows)->get('users')->as_array();
		}
	}

	private function _myIndexSidebar()
	{
		$this->template->content->bind('following',$following);
		$this->template->content->bind('beingfollowed',$beingfollowed);
		$followMod = ORM::factory('follow');
		//我follow的用户
		$followers = $followMod->where(array('user_id'=>$this->session->get('userId')))->find_all();
		$follows = array();
		foreach($followers as $follower)
		{
			$follows[] = $follower->follow_id;
		}	

		if(!empty($follows))
		{
			$following = Database::instance()->select('id','username','email')->in('id',$follows)->get('users')->as_array();
		}

		//谁关注这个人
		$followers = $followMod->where(array('follow_id'=>$this->session->get('userId')))->find_all();
		$follows = array();
		foreach($followers as $follower)
		{
			$follows[] = $follower->user_id;
		}	

		if(!empty($follows))
		{
			$beingfollowed = Database::instance()->select('id','username','email')->in('id',$follows)->get('users')->as_array();
		}

	}
}
